from netmiko import ConnectHandler
import os
import time

LogTime = time.strftime('%Y-%m-%d_%H-%M-%S') 

#读取IP地址、用户名、密码。
#DEVICES = []#每台设备的地址、用户名、密码组成字典，所有设备存放在DEVICES列表中
def get_devices_info(path):  #参数是配置文件的路径  
    DEVICES = []
    try:
        with open(path, 'r') as f:
            for line in f:
                if line[0] == '#':   #忽略注释行
                    continue
                elif len(line) == 1: #忽略空行(len('\n')==1)
                    continue
                else:
                    info_list = (line.strip().split())
                    info_dict = {'ip':info_list[0],'username':info_list[1],'password':info_list[2]}
                    DEVICES.append(info_dict)       
        return DEVICES
    except FileNotFoundError as e:
        print('找不到设备的配置文件')
    except IndexError as e:
        print('设备配置文件内容格式有误')
#       ip username password，3个值中间都有1个空格

#读取巡检命令
#CMD中包含所有巡检命令，以列表的形式存放
def get_cmd_info(path):
    CMD = []
    try:
        with open(path, 'r') as f:
            for line in f:
                if line[0] == '#':   #忽略注释行
                    continue
                elif len(line) == 1: #忽略空行(len('\n')==1)
                    continue
                else:                
                    CMD.append(line.strip())   
            return CMD
    except FileNotFoundError as e:
        print('找不到设备的配置文件')  
        
##执行巡检命令
def run_cmd(hosts=get_devices_info('DEVICES.cfg'),commands=get_cmd_info('CMD.cfg')):
#    print(hosts)
#    print(commands)
    if os.path.exists('fail.txt') == True:#先清除巡检失败记录
        os.remove('fail.txt')
    for i in hosts:    
        try:
            net_connect = ConnectHandler(device_type='cisco_ios',**i)
            current_ip = i['ip']
            #创建以设备名+时间为文件夹名的目录
            dirname = current_ip + '_' + LogTime
            os.mkdir(dirname)
            for j in commands:
                output = net_connect.send_command(j)
                time.sleep(1)#等待1秒        
                with open(dirname+'\\'+j+'.txt', "w") as f:
                    f.write(output)
            print('{}设备完成巡检'.format(i['ip']))
        except:
            print('{}设备巡检失败,记录保存在当前目录中的fail.txt'.format(i['ip']))
            with open('fail.txt', "a") as f:
                    f.write(i['ip']+'\n')
                   
if __name__=='__main__':            
    run_cmd()#默认根据cfg文件内容（IP、巡检命令）巡检







